from threading import Thread

from Dice import Dice
import Player

class Game (Thread):

    def __init__(self, players, board, xml, xsd):
        Thread.__init__(self)
        
        self.players = []
        self.dice = Dice(dices=1,seed=0,faces=2)
        self.board = board
        self.winner = []

        Player.Preload(self.dice, xml, xsd)

        for player in players:
            self.players.append(Player.PlayerGUI(player))
            self.board.AddPlayer(player[1])

    def start (self):
        Thread.start (self)
        Player.PlayerGUI.eventThread.start()

    def HasWinner(self):
        return len(self.winner) > 0

    def NextTurn(self):
        for player in self.players:
#            raw_input('press enter')
            print player.GetName(), "plays"
            while( True ):
                moves = self.dice.Throw()
                print "player got ", moves
                action = self.board.Move(player.GetId(), moves)
                print action
                response = player.Play(action, moves)
                result = self.board.Act(player.GetId(),response)
                print result            
                for player in self.players:
                    player.Inform(result)

                if( result.code == 'WIN'):
                    self.winner.append(player)
                elif( result.code == 'AGAIN' ):
                    continue
                break
            
    def run (self):
        while(not self.HasWinner()):
            print "Begin of Turn"
            self.NextTurn()
                
            

